//  新建班级的注释

<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
    </div>
    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="handleAdd" >新建</a-button>
    </div>
    <template>
      <s-table
          ref="table"
          size="default"
          :columns="columns"
          :data="loadData"
          :alert="{ show: true, clear: () => { this.selectedRowKeys = [] } }"
          :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      >

        <span slot="status" slot-scope="status,record">
        <a-badge status="success" v-if="status==1" text="显示" />
        <a-badge status="default" v-else text="隐藏" />
      </span>
        <span slot="action" slot-scope="text, record">
        <template >
          <a @click="handleEdit(record)" v-if="$auth('user.edit')">编辑</a>
          <a-divider type="vertical" />
            <a-popconfirm title="确定删除吗" @confirm="onDelete(record)"  okText="确定" cancelText="取消">
    <a href="javascript:;">删除</a>
            </a-popconfirm>
        </template>

      </span>
      </s-table>
    </template>
    <a-modal
            title="操作"
            :width="800"
            v-model="visible"
            @ok="handleOk"
    >
      <a-spin :spinning="saveLoading">
        <a-form :form="form">
          <a-form-item
                  label="学年"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
          >
            <a-select
                    optionFilterProp="title"
                    v-model="formData.year"
                    placeholder="选择学年"
            >
              <a-select-option :key="option.id" v-for="option in yearOptions"   :title="option.name" :disabled="option.disabled" :value="option.name">{{option.name}}</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="名称"
                  hasFeedback
          >
            <a-input v-decorator="[
          'name',
          {rules: [{ required: true, message: '请输入班级名称' }]}
        ]"
                     placeholder="请输入班级名称"/>
          </a-form-item>
          <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="状态"
                  hasFeedback
          >
            <r-switch  :formData="formData" field="status" :checkedValue="1" :unCheckedValue="2"  checkedChildren="显示" unCheckedChildren="隐藏" />
          </a-form-item>
        </a-form>
      </a-spin>
      <template slot="footer">
        <a-button key="cancel" @click="handleCancel">取消</a-button>
        <a-button key="forward" :loading="saveLoading" type="primary" @click="handleOk">保存</a-button>
      </template>
    </a-modal>

  </a-card>
</template>

<script>
  import moment from 'moment'
  import EditableCell from '@/components/EditableCell/'
  import STable from '@/components/table/'
  import { getClazzList,yearOptions,clazzAdd,clazzEdit,clazzDetail,clazzDelete } from '@/api/clazz'
  import PicUploader from '@/components/PicUploader/'
  import RSwitch from '@/components/RSwitch/'
  import {getUserList} from "@/api/user";

  export default {
    name: 'SubjectList',
    components: {
      PicUploader,EditableCell,RSwitch,STable
    },
    data () {
      return {
        saveLoading:false,
        visible: false,
//        description: '全校班级管理。',
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 12 },
        },
        form: this.$form.createForm(this),
        mdl: {},

        // 高级搜索 展开/关闭
        advanced: false,
        // 查询参数
        queryParam: {
          pageNo:1,
        },
        // 表头
        columns: [
          {
            title: '名称',
            dataIndex: 'name',
            scopedSlots: { customRender: 'name' },
          },
          {
            title: '学年',
            dataIndex: 'year',
          },
          {
            title: '状态',
            dataIndex: 'status',
            scopedSlots: { customRender: 'status' },
          },
          {
            table: '操作',
            dataIndex: 'action',
            width: '250px',
            scopedSlots: { customRender: 'action' },
          }
        ],

        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          console.log('loadData');
          console.log(this.queryParam);
          this.queryParam = Object.assign(this.queryParam,parameter);
          console.log("hahahhahahahha");
          return getClazzList(this.queryParam)
              .then(res => {
                console.log('res');
                return res.data
              })
        },
        list:[

        ],
        subjectOptions:[
        ],
        yearOptions:[
        ],
        formData:{
          name:'',
          version_id:undefined,
          id:0,
          rank:0,
          status:1,
        },
        selectedRowKeys: [],
        selectedRows: [],
      }
    },
    created () {
//      getRoleList({ t: new Date()})
    },
    computed:{
    },
    mounted(){
      let that = this;
      that.getYearOptions();
    },
    methods: {
      getYearOptions(){
        let that = this;
        yearOptions()
                .then(res => {
                  console.log(res)
                  that.yearOptions =  res.data
                })
      },

      onSelectChange (selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
      },
      handleCancel(){
        this.visible = false
      },
      // 增
      handleAdd(record) {
        let that = this;
        that.visible = true;
        that.form.resetFields();
        that.formData = {
          name:'',
          version_id:undefined,
          id:0,
          rank:0,
          status:1,
        }
        setTimeout( () =>{
          that.form.setFieldsValue({ ...that.formData });
        });
      },
      // 改
      handleEdit(record) {
        let self = this
        this.visible = true
//      this.form.resetFields();
        self.form.setFieldsValue({
          name:'',
        });
        this.formData.id = record.id;
        clazzDetail({ id: record.id }).then(res => {
          setTimeout(()=>{
            self.form.setFieldsValue({...res.data});
          },1)
          self.formData = {...res.data};
        })
        // console.log(this.mdl)
      },
      // 增改 处理
      handleOk(e) {
        let self = this
        e.preventDefault()
        this.form.validateFields((err, values) => {
          if (!err) {
            if(!self.formData.year){
              self.$message.error('请选择学年');
              return ;
            }
            console.log('Received values of form: ', values)
            console.log('Received valuess of formData: ', self.formData)
            self.saveLoading = true;
            if(self.formData.id) {
              clazzEdit({
                name:values.name,
                status:self.formData.status,
                id:self.formData.id,
                year:self.formData.year,
              }).then(res => {
                self.$message.success('修改成功')
                self.$refs.table.refresh(true)
                self.visible = false;
                self.saveLoading = false;
              }).catch(err =>{
                self.$message.error(err.data.msg);
                self.saveLoading = false;
              })
            }else{
              clazzAdd({
                name:values.name,
                status:self.formData.status,
                year:self.formData.year,
              }).then(res => {
                self.$message.success('新增成功')
                self.$refs.table.refresh(true)
                self.visible = false
                self.saveLoading = false;
              }).catch(err =>{
                self.$message.error(err.data.msg);
                self.saveLoading = false;
              })
            }
          }
        })
      },
      // 删
      onDelete(record) {
        let self = this
        clazzDelete({ id: record.id  }).then(res => {
          self.$message.success('删除成功')
          self.$refs.table.refresh(true)
        }).catch(err =>{
          self.$message.error(err.data.msg)
        })
      },
      cateParentsIds(cate_id){
        let self = this;
        let parent_id = cate_id;
        let parents_ids = [];
        while(parent_id != 0){
          cate_id = parent_id;
          parent_id = self.getListParentId(cate_id);
          if(parent_id >0){
            parents_ids.push(parent_id+'');
            continue;
          }
          break;
        }
        return parents_ids.reverse(parents_ids);
      },
      getListParentId(cate_id){
        let self = this;
        let parent_id = 0;
        self.cateList.map(function (item) {
          if(item.id == cate_id){
            parent_id = item.parent_id
            return ;
          }
        })
        return parent_id;
      },

      onRankChange(key, dataIndex, value) {
        let self = this;
        setSubjectRank({
          id: key,
          rank:value
        }).then(res => {
          self.fetch();
        }).catch(err =>{
          self.$message.error(err.data.msg)
        })
      },
    },
    watch: {
      /*
       'selectedRows': function (selectedRows) {
       this.needTotalList = this.needTotalList.map(item => {
       return {
       ...item,
       total: selectedRows.reduce( (sum, val) => {
       return sum + val[item.dataIndex]
       }, 0)
       }
       })
       }
       */
    }
  }
</script>